package com.css.order.controller;

import com.css.order.VO.ResultVO;
import com.css.order.client.ProductClient;
import com.css.order.converter.OrderForm2OrderDTOConverter;
import com.css.order.dto.CartDTO;
import com.css.order.dto.OrderDTO;
import com.css.order.enums.ResultEnum;
import com.css.order.exception.OrderException;
import com.css.order.form.OrderForm;
import com.css.order.service.OrderService;
import com.css.order.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ResultVO create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO convert = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(convert.getOrderDetailList())) {
            throw new OrderException(ResultEnum.CART_EMPTY);
        }

        OrderDTO orderDTO = orderService.create(convert);
        Map<String, String> map = new HashMap<>(16);
        map.put("orderId", orderDTO.getOrderId());
        return ResultVOUtil.success(map);
    }


}
